<template>
  <div class="xh-content">
    <!-- 提示 -->
    <section v-if="status === 1" class="xh-message-text">{{ message }}</section>
    <!-- 显示短链接和二维码图片 -->
    <section v-if="status === 3" class="xh-clink">
      <div class="short-link">
        短链接：<a :href="shortUrl" class="short-link-text">{{ shortUrl }}</a>
      </div>
      <div class="short-qrcode">
        二维码：
        <span ref="qrcode" />
      </div>
    </section>
  </div>
</template>
<script lang="ts">
import QRCode from "QRCode";
import { Component, Vue } from "vue-property-decorator";
import { Config } from "../interface/publicInterface";

@Component({})
export default class ResultBox extends Vue {
  public status = 0; // 0 none 1 error 2 loading 3 finished
  public message = "";
  public shortUrl = "";
  public longUrl = "";
  public loading: any = null;
  public QRCode: HTMLElement | null = null;

  mounted(): void {
    this.init();
  }

  init(): void {
    this.$bus.$on("sendLongUrl", (config: Config) => {
      const { longUrl, message, status } = config;
      this.status = 0;
      this.message = "未知的错误！";
      this.QRCode && ((this.$refs.qrcode as HTMLElement).innerHTML = "");
      if (!status) {
        this.message = message;
        this.status = 1;
      } else {
        this.status = 2; // 发送请求
        this.requestShortUrl(longUrl);
      }
    });
  }

  requestShortUrl(link: string): void {
    this.loading = this.$loading({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    fetch("http://www.sphjy.com/api/url/shorten", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        longURL: link,
      }),
    })
      .then((res: any): any => res.json())
      .then((res: any): void => {
        this.status = 3;
        this.shortUrl = res.shortUrl;
        // 生成二维码
        this.getQRCode();
      })
      .catch((e: any) => {
        this.status = 1;
        this.message = e.message;
      })
      .finally((): void => {
        this.loading.close();
        this.loading = null;
      });
  }

  getQRCode(): void {
    this.$nextTick(() => {
      this.QRCode = new QRCode(this.$refs.qrcode, {
        text: this.shortUrl,
        width: 128,
        height: 128,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
    });
  }
}
</script>
<style scoped lang="stylus">
.xh-content {
  width: 800px;
  margin: 0 auto;
}

.short-link {
  height: 80px;
  align-items: center;
  display: flex;
  text-align: left;
}

.short-qrcode {
  height: 150px;
  align-items: center;
  display: flex;
  text-align: left;
}
</style>
